package com.haiyou.data.sdk.account;

import org.redisson.api.RAtomicLong;

import com.haiyou.common.entity.Prefix;
import com.haiyou.common.system.Properties;
import com.haiyou.data.common.accessor.annotation.CachedPolicy;
import com.haiyou.data.common.accessor.annotation.ExpiryPolicy;
import com.haiyou.data.common.accessor.redis.redisson.bucket.BucketAccessor;
import com.haiyou.data.common.cache.redis.RKeys;
import com.haiyou.data.common.cache.redis.key.RedisPrefix;

@CachedPolicy(expiryPolicy = @ExpiryPolicy(timeToLive = -1))
@Prefix(RedisPrefix.ACCOUNT)
public class SdkAccountTableAccessor extends BucketAccessor<SdkAccountTable>{

	private String uidKeyPrefix;

	@Override
	public void init() {
		super.init();
		uidKeyPrefix = getKeyPrefix() + "_uid";
	}
	
	/**
	 * uid 生成器
	 * @return
	 */
	public RAtomicLong uidCreator() {
		RAtomicLong atomicLong = getRedissonClient()
				.getAtomicLong(RKeys.createRKey(RAtomicLong.class, uidKeyPrefix, "keyGenerator"));
		if (atomicLong.get() == 0L) {
			//账号系统 uid 起始位置
			//long begin = getKeyPersist(uidKeyPrefix, uidBeginNumberId());
			long begin = uidBeginNumberId();
			atomicLong.compareAndSet(0L, begin == 0L ? 0 : begin);
		}
		
		return atomicLong;
	}

	
	
	/**
	 * uid 生成起始配置
	 * @return
	 */
	public long uidBeginNumberId() {
		return Properties.account_uid_begin_number_id();
	}

	/**
	 * 生成下一个Uid
	 * @return
	 */
	public String uidNext() {
		return String.valueOf(uidCreator().incrementAndGet());
	}

	

	@Override
	public void destory() {
		super.destory();
		//persistKeyValue(uidKeyPrefix, uidCreator().get());
	}
	
	
	
	
}
